{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义文档集合\n",
    "documents = [\n",
    "    \"Hello there good man!\",\n",
    "    \"It is quite windy in London\",\n",
    "    \"How is the weather today?\"\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## TF-IDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文档ID: 2, 得分: 0.4674, 文档内容: How is the weather today?\n",
      "文档ID: 0, 得分: 0.0000, 文档内容: Hello there good man!\n",
      "文档ID: 1, 得分: 0.0000, 文档内容: It is quite windy in London\n"
     ]
    }
   ],
   "source": [
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.metrics.pairwise import linear_kernel\n",
    "\n",
    "\n",
    "# 初始化TF-IDF向量化器\n",
    "vectorizer = TfidfVectorizer()\n",
    "\n",
    "# 计算TF-IDF矩阵\n",
    "tfidf_matrix = vectorizer.fit_transform(documents)\n",
    "\n",
    "# 准备查询\n",
    "query = \"windy London\"\n",
    "\n",
    "# 将查询转换为TF-IDF向量\n",
    "query_vec = vectorizer.transform([query])\n",
    "\n",
    "# 计算查询与文档之间的余弦相似度\n",
    "cosine_similarities = linear_kernel(query_vec, tfidf_matrix).flatten()\n",
    "\n",
    "# 打印出搜索结果，包括文档ID和得分\n",
    "results = list(enumerate(cosine_similarities))\n",
    "results.sort(key=lambda x: x[1], reverse=True)\n",
    "\n",
    "# 打印结果\n",
    "for doc_id, score in results:\n",
    "    print(f\"文档ID: {doc_id}, 得分: {score:.4f}, 文档内容: {documents[doc_id]}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## BM25"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.         0.         0.51082562]\n"
     ]
    }
   ],
   "source": [
    "from rank_bm25 import BM25Okapi\n",
    "import numpy as np\n",
    "\n",
    "# 分词\n",
    "tokenized_corpus = [doc.split() for doc in documents]\n",
    "\n",
    "# 初始化BM25模型\n",
    "bm25 = BM25Okapi(tokenized_corpus)\n",
    "\n",
    "# 计算查询与文档的相关性得分\n",
    "query = \"windy London\"\n",
    "tokenized_query = query.split(\" \")\n",
    "results = bm25.get_scores(tokenized_query)\n",
    "print(results)  \n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
